﻿using CMS.Auth;
using CMS.DataAccess;
using CMS.Model;
using CMS.ServiceProvider;
using CMS.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.DependencyInjection;
using System.Data;

namespace CMS.Controllers
{
    public class RptController:MyController
    {
        [HttpGet, MyAuthorize(false)]
        public virtual ResponseData SumSchedule(string period)
        {
            ReportLoader reportLoader = new ReportLoader();
            var user = ServiceLoader.GetService<OptUser>();
            string sql = "select * from tb_sum_by_teacher where period = @period";
            if (!user.IsAdm)
                sql += $" and teacher = '{user.UserId}'";
            var data= reportLoader.LoadSql(sql, new SqliteParameter("@period", period));
            var result = new ResponseData(data);
            return result;
        }

        [HttpPost, MyAuthorize(false)]
        public virtual ResponseData DiffSchedule(dynamic data)
        {
            var stSp = ServiceLoader.GetService<ScheduleTemplateServiceProvider>();
            var sSp = ServiceLoader.GetService<ScheduleServiceProvider>();
            string cls = data.dseClass?.ToString()!;
            string start = data.start?.ToString()!;
            string end = data.end?.ToString()!;
            var d_start = DateTime.Parse(start);
            var d_end = DateTime.Parse(end);
            var plan = stSp.ListByClass(cls);
            var actual = sSp.ListByClass(cls, start, end);
            var current = d_start;
            DataTable dt = new DataTable();
            dt.Columns.Add("date");
            dt.Columns.Add("weekday");
            dt.Columns.Add("plan");
            dt.Columns.Add("actual");
            dt.Columns.Add("note");
            var allCourse = new DbQuery<CourseModel>().List();
            while (current <= d_end)
            {
                AddRow(dt, current, allCourse, actual, plan);
                current = current.AddDays(1);
            }
            return new ResponseData(dt);
        }
        
        private void AddRow(DataTable dt,DateTime current,IList<CourseModel> course, IList<ScheduleModel> actual, IList<ScheduleTemplateModel> plan)
        {
            var currentStr = current.ToString("yyyy-MM-dd");
            for (int i = 1; i <= 15; i++)//目前最大每天课节数暂定为15天
            {
                var actuals = actual.Where(r => r.Date == currentStr && r.Seq == i).ToList();
                var plans = plan.Where(r => r.WeekDay == current.DayOfWeek && r.Seq == i).ToList();
                if (actuals.Count() == 0 && plans.Count() == 0) continue;
                actuals.Sort((a, b) => a.Course.CompareTo(b.Course));
                plans.Sort((a, b) => a.Course.CompareTo(b.Course));
                
                string planInfo = String.Join(",", plans.Select(r=>course.First(s=>s.Pk==r.Course).CourseName));
                string actualInfo = String.Join(",", actuals.Select(r => course.First(s => s.Pk == r.Course).CourseName));
                if (planInfo == actualInfo) continue;
                var row = dt.Rows.Add();
                string noteInfo = String.Join(",", actuals.Select(r => String.IsNullOrWhiteSpace(r.Note) ? null : $"[{course.First(s => s.Pk == r.Course).CourseName}]{r.Note}"));
                if (noteInfo.Replace(",", "") == "")
                    noteInfo = "";
                row["date"] = currentStr;
                row["weekday"] = current.DayOfWeek;
                row["plan"] = planInfo;
                row["actual"] = actualInfo;
                row["note"] = noteInfo;
            }
        }
    }
}
